/* (c) 2014 Open Source Geospatial Foundation - all rights reserved
 * (c) 2012 - 2013 OpenPlans
 * This code is licensed under the GPL 2.0 license, available at the root
 * application directory.
 */
package org.geoserver.security;

import java.util.Map;
import org.geoserver.ows.URLMangler;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/** Re-injects the eventual authentication key in all backlinks generated by GeoServer */
public class AuthenticationKeyMangler implements URLMangler {

    @Override
    public void mangleURL(
            StringBuilder baseURL, StringBuilder path, Map<String, String> kvp, URLType type) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof KeyAuthenticationToken) {
            KeyAuthenticationToken kat = (KeyAuthenticationToken) authentication;
            String key = (String) kat.getCredentials();
            kvp.put(kat.getAuthKeyParamName(), key);
        }
    }
}
